import 'dart:ui';
import 'package:canteen/class/dish.dart';
import 'package:canteen/class/set_meal.dart';
import 'package:canteen/class/order.dart';
import 'package:canteen/dio/order_dio.dart';
import 'package:canteen/method/showDialog.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:canteen/component/my_button.dart';
import 'package:canteen/method/find_by_name.dart';
import 'package:canteen/menu_c_v.dart';
import 'package:canteen/dio/configure_dio.dart';
import 'package:canteen/history_c_v.dart';

class CalculatePage extends StatefulWidget {
  const CalculatePage({super.key});

  static const String id = 'calculate_page';

  @override
  State<CalculatePage> createState() => _CalculatePageState();
}

class _CalculatePageState extends State<CalculatePage> {
  String selectedValue1 = '';
  String selectedValue2 = '';
  bool isSave = false;
  int choice1 = 0;
  int choice2 = 0;
  late Order order;
  late Map<SetMeal, int> setMeals;
  late Map<Dish, int> dishes;
  Map<String, List<String>> choice = {};
  List<String> choiceF = [];
  Map<String, String> ingredient = {};
  Map<String, Map<String, Map<String, String>>> menu = {
    '材料': {'全部': {}, '荤料': {}, '素料': {}},
    '菜品': {'全部': {}, '单点': {}, '套餐': {}},
  };

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    choice = menu.map((key, value) => MapEntry(key, value.keys.toList()));
    choiceF = choice.keys.toList();
    selectedValue1 = choiceF[0];
    selectedValue2 = choice[selectedValue1]![0];
    if (selectedValuePR == '') {
      selectedValuePR = privateRooms[0];
    }
    if (selectedTime == '') {
      selectedTime = time[0];
    }
    if (date == '') {
      date = DateTime.now().toString().substring(0, 10);
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    getDishesNum();
  }

  Future<void> getDishesNum() async {
    //fetch data from last page
    final Map<String, dynamic>? args =
        ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    Map<String, int> dishesNum = args?['dishesNum'];
    Map<String, int> setMealsNum = args?['setMealsNum'];
    dishes = dishesNum
        .map((key, value) => MapEntry(findDishByName(key, allDishes)!, value));
    setMeals = setMealsNum.map(
        (key, value) => MapEntry(findSetMealByName(key, allSetMeals)!, value));
    //generate a order
    order = Order(dishes: dishes, setMeals: setMeals);
    //update the menu
    menu['菜品']?['单点'] =
        dishesNum.map((key, value) => MapEntry(key, '$value 份'));
    menu['菜品']?['套餐'] =
        setMealsNum.map((key, value) => MapEntry(key, '$value 份'));
    order.totalIngredients.forEach((key, value) {
      menu['材料']![key.type]?[key.name] =
          '${value.toStringAsFixed(2)} ${key.unit}';
      menu['材料']!['全部']?[key.name] = '${value.toStringAsFixed(2)} ${key.unit}';
    });
    order.totalDishes.forEach((key, value) {
      menu['菜品']!['全部']?[key.name] = '$value 份';
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffbfbfb),
      appBar: AppBar(
        backgroundColor: Color(0xffffffff).withOpacity(0.89),
        elevation: 0,
        centerTitle: true,
        title: Text(
          '确认订单',
          style: TextStyle(color: Colors.black, fontSize: 16),
        ),
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_rounded,
            color: Colors.black,
          ),
        ),
      ),
      body: Column(
        children: [
          Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.symmetric(horizontal: 30, vertical: 6),
            child: Text(
              '信息',
              style: TextStyle(fontSize: 16),
            ),
          ),
          Container(
            margin: EdgeInsets.symmetric(horizontal: 20),
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20),
                border:
                    Border.all(color: Colors.black.withOpacity(0.5), width: 2)),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Container(
                          height: 15,
                          width: 15,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(
                                color: Colors.black.withOpacity(0.6),
                                width: 0.5),
                          ),
                        ),
                        Text('订单时间'),
                      ],
                    ),
                    Row(
                      children: [
                        GestureDetector(
                          onTap: () async {
                            // 调用日期选择器
                            DateTime? pickedDate = await showDatePicker(
                              context: context,
                              initialDate: DateTime.now(),
                              firstDate: DateTime.now(),
                              // 将 lastDate 设置为当前时间一年后
                              lastDate: DateTime.now().add(Duration(days: 365)),
                              textDirection: TextDirection.ltr,
                              currentDate: DateTime.now(),
                              cancelText: "取消",
                              confirmText: "确定",
                              errorFormatText: "格式错误",
                              errorInvalidText: "输入日期无效",
                              fieldLabelText: "month/day/year",
                              fieldHintText: "月/日/年",
                              initialDatePickerMode: DatePickerMode.day,
                              useRootNavigator: true,
                            );
                            // 如果选择了日期，则更新 date 变量
                            if (pickedDate != null) {
                              setState(() {
                                date = pickedDate.toString().substring(0, 10);
                              });
                            }
                          },
                          child: Text(
                            date,
                            style: TextStyle(
                              fontSize: 16,
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 6),
                          child: DropdownButton(
                              isDense: true,
                              elevation: 1,
                              borderRadius: BorderRadius.circular(15),
                              underline: SizedBox(),
                              icon: SizedBox(),
                              value: selectedTime,
                              items: time
                                  .map(
                                    (e) => DropdownMenuItem(
                                      value: e,
                                      child: Text(
                                        e,
                                        style: TextStyle(
                                          color: Color(0xff2b3d85),
                                        ),
                                      ),
                                    ),
                                  )
                                  .toList(),
                              onChanged: (value) {
                                setState(() {
                                  selectedTime = value!;
                                });
                              }),
                        ),
                      ],
                    ),
                  ],
                ),
                SizedBox(
                  height: 8,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Container(
                          height: 15,
                          width: 15,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(
                                color: Colors.black.withOpacity(0.6),
                                width: 0.5),
                          ),
                        ),
                        Text('查看类型'),
                      ],
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 6),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          border:
                              Border.all(color: Color(0xff6486f3), width: 2)),
                      child: DropdownButton(
                          isDense: true,
                          elevation: 1,
                          borderRadius: BorderRadius.circular(15),
                          underline: SizedBox(),
                          icon: SizedBox(),
                          value: selectedValue1,
                          items: choiceF
                              .map(
                                (e) => DropdownMenuItem(
                                  value: e,
                                  child: Text(
                                    e,
                                    style: TextStyle(
                                      color: Color(0xff2b3d85),
                                    ),
                                  ),
                                ),
                              )
                              .toList(),
                          onChanged: (value) {
                            setState(() {
                              selectedValue1 = value!;
                              choice1 = choiceF.indexOf(selectedValue1);
                              selectedValue2 = choice[selectedValue1]![0];
                            });
                          }),
                    ),
                  ],
                ),
                SizedBox(
                  height: 8,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Container(
                          height: 15,
                          width: 15,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(
                                color: Colors.black.withOpacity(0.6),
                                width: 0.5),
                          ),
                        ),
                        Text('包房'),
                      ],
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          border:
                              Border.all(color: Color(0xff6486f3), width: 2)),
                      child: Text(
                        selectedValuePR,
                        style: TextStyle(color: Color(0xff2b3d85)),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(
            height: 15,
          ),
          Expanded(
            child: Stack(
              children: [
                Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          width: 80,
                          height: 30,
                          margin: EdgeInsets.only(left: 20),
                          padding: EdgeInsets.only(top: 3),
                          decoration: BoxDecoration(
                            border: Border.all(
                                color: Colors.black.withOpacity(0.5), width: 2),
                            color: Colors.white,
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(10),
                              topLeft: Radius.circular(10),
                            ),
                          ),
                          child: Row(
                            children: [
                              Container(
                                height: 15,
                                width: 15,
                                margin: EdgeInsets.only(left: 10, right: 6),
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  border: Border.all(
                                      color: Colors.black.withOpacity(0.6),
                                      width: 0.5),
                                ),
                              ),
                              Text(
                                '订单',
                                style: TextStyle(fontSize: 16),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    Expanded(
                      child: AnimatedSwitcher(
                        duration: Duration(milliseconds: 200),
                        child: Container(
                          key: ValueKey(menu[selectedValue1]![selectedValue2]),
                          margin: EdgeInsets.symmetric(horizontal: 20),
                          decoration: BoxDecoration(
                            border: Border.all(
                                color: Colors.black.withOpacity(0.5), width: 2),
                            color: Colors.white,
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(25),
                              bottomRight: Radius.circular(25),
                              bottomLeft: Radius.circular(25),
                            ),
                          ),
                          child: Column(
                            children: [
                              SizedBox(
                                height: 8,
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: choice[selectedValue1]!
                                    .map((e) => GestureDetector(
                                          onTap: () {
                                            setState(() {
                                              selectedValue2 = e;
                                            });
                                          },
                                          child: Container(
                                            padding: EdgeInsets.symmetric(
                                                horizontal: 8, vertical: 3),
                                            child: Text(
                                              e,
                                              style: TextStyle(
                                                color: selectedValue2 == e
                                                    ? Color(0xff6486f3)
                                                    : Colors.black,
                                              ),
                                            ),
                                            decoration: BoxDecoration(
                                              border: selectedValue2 == e
                                                  ? Border.all(
                                                      color: Color(0xff6486f3),
                                                      width: 1)
                                                  : null,
                                              borderRadius:
                                                  BorderRadius.circular(5),
                                            ),
                                          ),
                                        ))
                                    .toList(),
                              ),
                              Container(
                                height: 1,
                                color: Colors.black.withOpacity(0.18),
                                margin: EdgeInsets.symmetric(
                                    horizontal: 15, vertical: 8),
                              ),
                              Expanded(
                                child: ListView.builder(
                                    padding: EdgeInsets.zero,
                                    itemCount:
                                        menu[selectedValue1]![selectedValue2]
                                            ?.length,
                                    itemBuilder: (context, index) {
                                      return Container(
                                        margin: EdgeInsets.symmetric(
                                            horizontal: 15),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text(
                                              menu[selectedValue1]![
                                                      selectedValue2]!
                                                  .keys
                                                  .toList()[index],
                                              style: TextStyle(fontSize: 16),
                                            ),
                                            Text(
                                              '${menu[selectedValue1]![selectedValue2]?.values.toList()[index]}',
                                              style: TextStyle(fontSize: 16),
                                            )
                                          ],
                                        ),
                                      );
                                    }),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                Positioned(
                  child: Container(
                    height: 4,
                    width: 76,
                    color: Colors.white,
                  ),
                  left: 22,
                  top: 28,
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(bottom: 15, top: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                MyButton(
                  onClick: () {
                    Navigator.pop(context);
                  },
                  child: Text(
                    '取消',
                    style: TextStyle(color: Colors.white, fontSize: 20),
                  ),
                  boxDecoration: BoxDecoration(
                    color: Color(0xff6486f3),
                    borderRadius:
                        BorderRadius.circular(20), // 设置圆角半径，你可以根据需要调整这个值
                  ),
                  size: [100, 45],
                ),
                MyButton(
                  onClick: () {
                    saveOrder();
                  },
                  child: Text(
                    '保存',
                    style: TextStyle(color: Colors.white, fontSize: 20),
                  ),
                  boxDecoration: BoxDecoration(
                    color: Color(0xff6486f3),
                    borderRadius:
                        BorderRadius.circular(20), // 设置圆角半径，你可以根据需要调整这个值
                  ),
                  size: [100, 45],
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  void saveOrder() async {
    order.pRoom = selectedValuePR;
    if (ordersWithDate[date] == null) {
      ordersWithDate[date] = {};
    }
    List<Order> orderList = ordersWithDate[date]?[selectedTime] ?? [];
    int existingIndex = orderList
        .indexWhere((existingOrder) => existingOrder.pRoom == order.pRoom);
    try {
      if (existingIndex == -1) {
        Response response = await addOrder(order: {
          'name': '$date $selectedTime $selectedValuePR',
          "date": "$date $selectedTime",
          "dishCount":
              order.dishes.map((key, value) => MapEntry(key.name, value)),
          "setMealCount":
              order.setMeals.map((key, value) => MapEntry(key.name, value)),
          "privateRoomName": selectedValuePR
        }, dio: dio);
        order.id = response.data['data'];
        orderList.add(order);
      } else {
        order.id = orderList[existingIndex].id;
        await updateOrder(order: {
          'name': '$date $selectedTime $selectedValuePR',
          "date": "$date $selectedTime",
          "dishCount":
              order.dishes.map((key, value) => MapEntry(key.name, value)),
          "setMealCount":
              order.setMeals.map((key, value) => MapEntry(key.name, value)),
          "privateRoomName": selectedValuePR,
          "id": order.id,
        }, dio: dio);
        orderList[existingIndex] = order;
      }
      ordersWithDate[date]?[selectedTime] = orderList;
      ShowDialog.showCorrectAndDetail(context, '上传成功');
    } on Exception catch (e) {
      print(e);
      ShowDialog.showErrorAndDetail(context, '上传失败');
    }
  }
}
/*

Positioned.fill(
child: CustomPaint(
painter: GradientPainter(
xS: 0,
yS: 0,
heightMul: 0.2,
colorList: [
Color(0xff94F8FF),
Color(0xffF7D2FF),
Color(0xffF7D1FF),
Color(0xffFFD8AC),
],
),
),
),
BackdropFilter(
filter: ImageFilter.blur(sigmaX: 1000, sigmaY: 60),
child: Container(),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 40),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
GestureDetector(
onTap: () async {
// 调用日期选择器
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
// 将 lastDate 设置为当前时间一年后
lastDate: DateTime.now().add(Duration(days: 365)),
textDirection: TextDirection.ltr,
currentDate: DateTime.now(),
cancelText: "取消",
confirmText: "确定",
errorFormatText: "格式错误",
errorInvalidText: "输入日期无效",
fieldLabelText: "month/day/year",
fieldHintText: "月/日/年",
initialDatePickerMode: DatePickerMode.day,
useRootNavigator: true,
);
// 如果选择了日期，则更新 date 变量
if (pickedDate != null) {
setState(() {
date = pickedDate.toString().substring(0, 10);
});
}
},
child: Text(
date,
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold),
),
),
SizedBox(
width: 25,
),
DropdownButton(
elevation: 1,
borderRadius: BorderRadius.circular(15),
menuMaxHeight: 150,
underline: SizedBox(),
icon: SizedBox(),
value: selectedValuePR,
items: privateRooms
    .map(
(e) => DropdownMenuItem(
value: e,
child: Text(
e,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold),
),
),
)
    .toList(),
onChanged: (value) {
setState(() {
selectedValuePR = value!;
});
}),
],
),
DropdownButton(
elevation: 1,
borderRadius: BorderRadius.circular(15),
underline: SizedBox(),
icon: SizedBox(),
value: selectedValue1,
items: choiceF
    .map(
(e) => DropdownMenuItem(
value: e,
child: Text(
e,
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold),
),
),
)
    .toList(),
onChanged: (value) {
setState(() {
selectedValue1 = value!;
choice1 = choiceF.indexOf(selectedValue1);
selectedValue2 = choice[selectedValue1]![0];
});
}),
],
),
),
DropdownButton(
elevation: 1,
borderRadius: BorderRadius.circular(15),
underline: SizedBox(),
icon: SizedBox(),
value: selectedValue2,
items: choice[selectedValue1]
    ?.map(
(e) => DropdownMenuItem(
value: e,
child: Text(
e,
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold),
),
),
)
    .toList(),
onChanged: (value) {
setState(() {
selectedValue2 = value!;
choice2 = choice[selectedValue1]!.indexOf(selectedValue2);
});
}),
 */

/*
  Future<void> exportToExcel() async {
    if (isSave) {
      return;
    }
    var excel = Excel.createExcel();
    Sheet sheetObject = excel['Sheet1'];

    // 设置表头样式
    CellStyle headerStyle = CellStyle(backgroundColorHex: ExcelColor.blue);
    sheetObject.cell(CellIndex.indexByString('A1')).value = TextCellValue('日期');
    sheetObject.cell(CellIndex.indexByString('A1')).cellStyle = headerStyle;
    sheetObject.cell(CellIndex.indexByString('B1')).value = TextCellValue('包房');
    sheetObject.cell(CellIndex.indexByString('B1')).cellStyle = headerStyle;
    sheetObject.cell(CellIndex.indexByString('C1')).value = TextCellValue('类型');
    sheetObject.cell(CellIndex.indexByString('C1')).cellStyle = headerStyle;
    sheetObject.cell(CellIndex.indexByString('D1')).value = TextCellValue('名称');
    sheetObject.cell(CellIndex.indexByString('D1')).cellStyle = headerStyle;
    sheetObject.cell(CellIndex.indexByString('E1')).value =
        TextCellValue('数量/单位');
    sheetObject.cell(CellIndex.indexByString('E1')).cellStyle = headerStyle;

    // 设置日期和包房单元格为黄色背景
    CellStyle yellowCellStyle =
        CellStyle(backgroundColorHex: ExcelColor.yellow);

    int rowIndex = 2;

    // 假设你有一个包含不同日期和包房组合的数据结构
    Map<String, Map<String, Map<String, String>>> dataByDateAndRoom = {};

    // 填充数据按日期和包房分组
    if (menu['材料']!['全部'] != null) {
      for (var entry in menu['材料']!['全部']!.entries) {
        var parts = entry.value.split(' ');
        var quantity = parts[0];
        var unit = parts[1];
        String key = '$date|${selectedValuePR}';
        if (!dataByDateAndRoom.containsKey(key)) {
          dataByDateAndRoom[key] = {'材料': {}, '菜品': {}};
        }
        dataByDateAndRoom[key]?['材料']![entry.key] = '$quantity $unit';
      }
    }

    if (menu['菜品']!['全部'] != null) {
      for (var entry in menu['菜品']!['全部']!.entries) {
        var parts = entry.value.split(' ');
        var quantity = parts[0];
        String key = '$date|${selectedValuePR}';
        if (!dataByDateAndRoom.containsKey(key)) {
          dataByDateAndRoom[key] = {'材料': {}, '菜品': {}};
        }
        dataByDateAndRoom[key]?['菜品']![entry.key] = quantity;
      }
    }

    // 写入数据到 Excel
    for (var dateRoomKey in dataByDateAndRoom.keys) {
      var [dateValue, roomValue] = dateRoomKey.split('|');
      var dataForThis = dataByDateAndRoom[dateRoomKey];
      sheetObject.cell(CellIndex.indexByString('A$rowIndex')).value =
          TextCellValue(dateValue);
      sheetObject.cell(CellIndex.indexByString('B$rowIndex')).value =
          TextCellValue(roomValue);
      sheetObject.cell(CellIndex.indexByString('A$rowIndex')).cellStyle =
          yellowCellStyle;
      sheetObject.cell(CellIndex.indexByString('B$rowIndex')).cellStyle =
          yellowCellStyle;
      if (dataForThis!['材料'] != null) {
        for (var materialEntry in dataForThis['材料']!.entries) {
          sheetObject.cell(CellIndex.indexByString('C$rowIndex')).value =
              TextCellValue('材料');
          sheetObject.cell(CellIndex.indexByString('D$rowIndex')).value =
              TextCellValue(materialEntry.key);
          sheetObject.cell(CellIndex.indexByString('E$rowIndex')).value =
              TextCellValue(materialEntry.value);
          rowIndex++;
        }
      }
      if (dataForThis['菜品'] != null) {
        for (var dishEntry in dataForThis['菜品']!.entries) {
          sheetObject.cell(CellIndex.indexByString('C$rowIndex')).value =
              TextCellValue('菜品');
          sheetObject.cell(CellIndex.indexByString('D$rowIndex')).value =
              TextCellValue(dishEntry.key);
          sheetObject.cell(CellIndex.indexByString('E$rowIndex')).value =
              TextCellValue(dishEntry.value);
          rowIndex++;
        }
      }
    }

    // 获取外部存储的公共下载目录路径
    final directory = await getExternalStorageDirectory();
    final filePath =
        '${directory!.path}/exported_data${DateTime.now().toString().substring(0, 19)}.xlsx';

    // 保存 Excel 文件
    await File(filePath).writeAsBytes(excel.save()!);

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),
            // side: BorderSide(color: Colors.tealAccent, width: 1),
          ),
          title: Text('提示'),
          content: Text('文件已保存，是否分享？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () async {
                // 使用 shareXFiles 进行分享
                await Share.shareXFiles([XFile(filePath)]);
                Navigator.of(context).pop();
              },
              child: Text('分享'),
            ),
          ],
        );
      },
    );
    isSave = true;
  }
 */
